<template>
  <div>
    <el-dialog
      class="custom-dialog"
      v-model="dialogVisible"
      :title="title"
      width="1300px"
      @close="handleClose"
    >
      <el-form
        class="data-form"
        ref="formRef"
        :model="form"
        :rules="rules"
        label-width="130px"
      >
        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="园区名称" prop="name">
              <el-input
                class="data-input"
                v-model="form.name"
                placeholder="请输入"
              ></el-input>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="园区地址" prop="address">
              <el-input
                class="data-input"
                v-model="form.address"
                placeholder="请输入"
              ></el-input>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="经纬度" prop="position">
              <el-input
                class="data-input1"
                v-model="form.position"
                placeholder="请输入"
              ></el-input>
              <el-button
                type="primary"
                @click="chooseLocationDialogVisible = true"
                >定位</el-button
              >
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="园区面积(m²)" prop="area">
              <el-input
                class="data-input"
                v-model="form.area"
                placeholder="请输入"
              ></el-input>
            </el-form-item>
          </el-col>
          <el-col :span="24">
            <el-form-item label="园区描述" prop="description">
              <el-input
                class="data-input"
                v-model="form.description"
                placeholder="请输入"
                type="textarea"
              ></el-input>
            </el-form-item>
          </el-col>
          <el-col :span="24">
            <el-form-item label="是否启用">
              <el-radio-group v-model="form.enable">
                <el-radio
                  v-for="(item, index) of dictOptions['yn']"
                  :key="index"
                  :value="item.value"
                  >{{ item.name }}</el-radio
                >
              </el-radio-group>
            </el-form-item>
          </el-col>
          <el-col :span="24">
            <el-form-item label="园区范围">
              <VUpload
                :limit="1"
                uploadText="点击上传范围文件"
                v-model="form.geojsonFile"
                width="250"
              />
            </el-form-item>
          </el-col>
          <el-col :span="24">
            <el-form-item label="园区图片">
              <VUpload
                listType="picture-card"
                uploadText=""
                accept=".png, .jpg, .jepg"
                v-model="form.files"
              />
            </el-form-item>
          </el-col>
        </el-row>
        <div class="title">
          土地信息
          <el-button type="primary" link @click="handleAdd"
            ><el-icon><CirclePlusFilled /></el-icon
          ></el-button>
        </div>
        <table>
          <thead>
            <tr>
              <th style="width: 130px">产权人</th>
              <th style="width: 130px">土地产权证号</th>
              <th style="width: 130px">宗地名称</th>
              <th style="width: 130px">土地面积(m²)</th>
              <th style="width: 130px">土地性质</th>
              <th style="width: 130px">土地用途</th>
              <th style="width: 130px">使用情况</th>
              <th style="width: 130px">使用年限</th>
              <th style="width: 130px">上传范围文件</th>
              <th style="width: 50px">操作</th>
            </tr>
          </thead>
          <tbody>
            <tr v-for="(item, index) of form.mapRegions" :key="index">
              <td style="width: 130px">
                <el-form-item
                  class="table-form-item"
                  label=""
                  :prop="'mapRegions.' + index + '.propertyOwner'"
                >
                  <el-select
                    class="data-input"
                    v-model="item.propertyOwner"
                    placeholder="请选择"
                    clearable
                  >
                    <el-option
                      v-for="(item, index) of dictOptions['propertyUnit']"
                      :key="index"
                      :label="item.name"
                      :value="item.value"
                    />
                  </el-select>
                </el-form-item>
              </td>
              <td style="width: 130px">
                <el-form-item
                  class="table-form-item"
                  label=""
                  :prop="'mapRegions.' + index + '.certificate'"
                  :rules="rules.landCertificate"
                >
                  <el-input
                    class="data-input"
                    v-model="item.certificate"
                    placeholder="请输入"
                  ></el-input>
                </el-form-item>
              </td>
              <td style="width: 130px">
                <el-form-item
                  class="table-form-item"
                  label=""
                  :prop="'mapRegions.' + index + '.name'"
                >
                  <el-input
                    class="data-input"
                    v-model="item.name"
                    placeholder="请输入"
                  ></el-input>
                </el-form-item>
              </td>
              <td style="width: 130px">
                <el-form-item
                  class="table-form-item"
                  label=""
                  :prop="'mapRegions.' + index + '.area'"
                  :rules="rules.landArea"
                >
                  <el-input
                    class="data-input"
                    v-model="item.area"
                    placeholder="请输入"
                  ></el-input>
                </el-form-item>
              </td>
              <td style="width: 130px">
                <el-form-item
                  class="table-form-item"
                  label=""
                  :prop="'mapRegions.' + index + '.character'"
                >
                  <el-select
                    class="data-input"
                    v-model="item.character"
                    placeholder="请选择"
                    clearable
                  >
                    <el-option
                      v-for="(item, index) of dictOptions['landNature']"
                      :key="index"
                      :label="item.name"
                      :value="item.value"
                    />
                  </el-select>
                </el-form-item>
              </td>
              <td style="width: 130px">
                <el-form-item
                  class="table-form-item"
                  label=""
                  :prop="'mapRegions.' + index + '.usage'"
                >
                  <el-select
                    class="data-input"
                    v-model="item.usage"
                    placeholder="请选择"
                    clearable
                  >
                    <el-option
                      v-for="(item, index) of dictOptions['landUse']"
                      :key="index"
                      :label="item.name"
                      :value="item.value"
                    />
                  </el-select>
                </el-form-item>
              </td>
              <td style="width: 130px">
                <el-form-item
                  class="table-form-item"
                  label=""
                  :prop="'mapRegions.' + index + '.useStatus'"
                >
                  <el-select
                    class="data-input"
                    v-model="item.useStatus"
                    placeholder="请选择"
                    clearable
                  >
                    <el-option
                      v-for="(item, index) of dictOptions['landUsage']"
                      :key="index"
                      :label="item.name"
                      :value="item.value"
                    />
                  </el-select>
                </el-form-item>
              </td>
              <td style="width: 130px">
                <el-form-item
                  class="table-form-item"
                  label=""
                  :prop="'mapRegions.' + index + '.useYear'"
                >
                  <el-date-picker
                    class="data-input"
                    v-model="item.useYear"
                    value-format="YYYY-MM-DD"
                    placeholder="请选择"
                  />
                </el-form-item>
              </td>
              <td style="width: 130px">
                <el-form-item
                  class="table-form-item"
                  label=""
                  :prop="'mapRegions.' + index + '.files'"
                >
                  <VUpload
                    uploadText="点击上传文件"
                    v-model="item.files"
                    :limit="1"
                    :limitShowButton="false"
                  />
                </el-form-item>
              </td>
              <td style="width: 50px">
                <el-form-item class="table-form-item" label="">
                  <el-button type="danger" link @click="handleRemove(index)"
                    ><el-icon><RemoveFilled /></el-icon
                  ></el-button>
                </el-form-item>
              </td>
            </tr>
          </tbody>
        </table>
      </el-form>
      <template #footer>
        <el-button @click="handleClose(false)" :loading="loading"
          >取消</el-button
        >
        <el-button type="primary" @click="handleSubmit" :loading="loading"
          >确定</el-button
        >
      </template>
    </el-dialog>
    <ChooseLocation
      v-model:dialog-visible="chooseLocationDialogVisible"
      :latlnt="form.position"
      @submitLocation="handleChooseLocation"
    />
  </div>
</template>
<script setup>
import { ref, watch, onMounted } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import { useDict } from '@/hooks/useDict'
const { dictOptions, initListDictOptions } = useDict()
import ChooseLocation from '@/components/chooseLocation.vue'
import VUpload from '@/components/upload/index.vue'
import { CirclePlusFilled, RemoveFilled } from '@element-plus/icons-vue'
import {
  parkAdd,
  parkUpdate,
  parkDetail,
  landDelete,
} from '@/api/manager/dataManage/park'
defineOptions({
  name: 'AddDialog',
})
const props = defineProps({
  detail: {
    type: Object,
  },
})
watch(
  () => props.detail,
  async () => {
    if (props.detail.pkid) {
      handleDetail()
    } else {
      form.value = { enable: '1', mapRegions: [] }
    }
  },
)
const handleDetail = async () => {
  const res = await parkDetail({ pkid: props.detail.pkid })
  if (res.success) {
    // 处理园区范围文件
    if (res.data.geoJsonFile) {
      res.data.geojsonFile = [res.data.geoJsonFile]
    } else {
      res.data.geojsonFile = []
    }
    // 处理园区图片
    res.data.files = res.data.fileList || []
    delete res.data.fileList
    delete res.data.geoJsonFile
    // 处理土地范围文件
    res.data.mapRegions.forEach((item) => {
      if (item.geoJsonFile) {
        item.files = [item.geoJsonFile]
      } else {
        item.files = []
      }
      delete item.geoJsonFile
    })
    form.value = { ...res.data }
  } else {
    ElMessage.error(res.message)
  }
}
const emit = defineEmits(['close'])
const title = ref('')
const dialogVisible = ref(false)
const handleClose = (isFlash) => {
  form.value = { enable: '1', mapRegions: [] }
  formRef.value.clearValidate()
  dialogVisible.value = false
  emit('close', isFlash)
}
const formRef = ref(null)
const form = ref({
  enable: '1',
  mapRegions: [],
})
const rules = ref({
  name: [{ required: true, message: '请输入园区名称', trigger: 'blur' }],
  address: [{ required: true, message: '请输入园区地址', trigger: 'blur' }],
  area: [
    { required: true, message: '请输入园区面积', trigger: 'blur' },
    {
      pattern: /^(?!0$)\d*(\.\d{1,2})?$/,
      message: '请输入带0-2位小数的正确数字',
      trigger: 'blur',
    },
  ],
  enable: [{ required: true, message: '请选择是否启用', trigger: 'blur' }],
  landCertificate: [
    { required: true, message: '请输入土地产权证号', trigger: 'blur' },
  ],
  landArea: [
    { required: true, message: '请输入土地面积', trigger: 'blur' },
    {
      pattern: /^(?!0$)\d*(\.\d{1,2})?$/,
      message: '请输入带0-2位小数的正确数字',
      trigger: 'blur',
    },
  ],
})

const loading = ref(false)
const handleSubmit = async () => {
  if (!formRef.value) return
  await formRef.value.validate(async (valid, fields) => {
    if (valid) {
      loading.value = true
      const params = JSON.parse(JSON.stringify(form.value))
      // 处理园区范围文件
      if (params.geojsonFile && params.geojsonFile.length > 0) {
        params.geojsonFileId = params.geojsonFile.map((i) => i.pkid).join(',')
      } else {
        params.geojsonFileId = ''
      }
      delete params.geojsonFile
      // 处理园区图片
      if (params.files && params.files.length > 0) {
        params.files = params.files
          .map((i) => {
            return i.pkid
          })
          .join(',')
      } else {
        params.files = ''
      }
      // 处理土地范围文件
      params.mapRegions.forEach((item) => {
        if (item.files && item.files.length > 0) {
          item.geojsonFileId = item.files.map((i) => i.pkid).join(',')
        } else {
          item.geojsonFileId = ''
        }
        delete item.files
      })

      try {
        let res
        if (form.value.pkid) {
          res = await parkUpdate(params)
        } else {
          res = await parkAdd(params)
        }
        if (res.success) {
          ElMessage.success('保存成功')
          handleClose(true)
        } else {
          ElMessage.error(res.message)
        }
        loading.value = false
      } catch (error) {
        console.log('error', error)
        loading.value = false
      }
    } else {
      ElMessage.warning('请正确录入信息')
    }
  })
}
const handleAdd = () => {
  form.value.mapRegions.push({
    name: '',
    propertyOwner: '',
    certificate: '',
    area: '',
    character: '',
    usage: '',
    useStatus: '',
    useYear: '',
    files: [],
  })
}
const handleRemove = (index) => {
  if (!form.value.mapRegions[index].pkid) {
    form.value.mapRegions.splice(index, 1)
  } else {
    ElMessageBox.confirm('是否确定删除该项？', '提示', {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning',
    })
      .then(async () => {
        const params = { pkid: form.value.mapRegions[index].pkid }
        const res = await landDelete(params)
        if (res.success) {
          ElMessage({
            type: 'success',
            message: '删除成功',
          })
          form.value.mapRegions.splice(index, 1)
        } else {
          ElMessage.error(res.message)
        }
      })
      .catch(() => {
        ElMessage({
          type: 'info',
          message: '已取消删除',
        })
      })
  }
}
const chooseLocationDialogVisible = ref(false)
const handleChooseLocation = (val) => {
  form.value.position = val.longitude + ',' + val.latitude
  chooseLocationDialogVisible.value = false
}
defineExpose({ dialogVisible, title })
onMounted(() => {
  initListDictOptions([
    'yn',
    'propertyUnit',
    'landNature',
    'landUse',
    'landUsage',
  ])
})
</script>
<style lang="scss" scoped>
.title {
  width: 100%;
  padding: 0 0 5px 15px;
  font-size: 14px;
  line-height: 14px;
  font-weight: 400;
  color: #151515;
  position: relative;
  &::before {
    content: ' ';
    position: absolute;
    width: 4px;
    height: 16px;
    background: linear-gradient(0deg, #4575ee 0%, #6297f5 100%);
    border-radius: 2px;
    top: 6px;
    left: 0px;
  }
  .el-button {
    margin-left: 10px;
  }
}
:deep(.table-form-item) {
  width: 100%;
  .el-form-item__content {
    margin-left: 0 !important;
  }
}
:deep(.data-input1) {
  width: calc(100% - 60px) !important;
}
table {
  th {
    height: 30px;
    text-align: left;
    padding: 0 5px;
  }
  td {
    padding: 0 5px;
  }
  tr {
    display: flex;
    td {
      display: flex;
      align-items: flex-start;
    }
  }
}
</style>
